import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { UserInfo, UserStatusUpdateParams } from './type'

export const useUserStore = defineStore('user', () => {
  // 当前登录用户信息
  const currentUser = ref<UserInfo | null>(null)

  // 登录令牌，存储在localStorage中实现持久化
  const token = ref<string | null>(localStorage.getItem('auth-token'))

  // 是否已登录
  const isLoggedIn = computed(() => !!token.value && currentUser.value !== null)

  // 设置用户信息
  const setUser = (user: UserInfo): void => {
    currentUser.value = user

    // 保存token到localStorage
    if (user.token) {
      token.value = user.token
      localStorage.setItem('auth-token', user.token)
    }
  }

  // 更新用户状态
  const updateStatus = (statusParams: UserStatusUpdateParams): void => {
    if (currentUser.value) {
      currentUser.value.status = statusParams.status
    }
  }

  // 登出
  const logout = (): void => {
    currentUser.value = null
    token.value = null
    localStorage.removeItem('auth-token')
  }

  // 获取用户头像
  const getUserAvatar = computed(() => {
    return (
      currentUser.value?.avatar ||
      'https://images.unsplash.com/photo-1535713875002-d1d0cf377fde?w=150&h=150&fit=crop&crop=center'
    )
  })

  // 获取用户昵称
  const getUserNickname = computed(() => {
    return currentUser.value?.nickname || currentUser.value?.username || '匿名用户'
  })

  return {
    currentUser,
    isLoggedIn,
    token,
    setUser,
    updateStatus,
    logout,
    getUserAvatar,
    getUserNickname
  }
})
